package com.kmxd.ams.app.event.efile.command;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.kmxd.ams.client.arrange.IDocumentSvc;
import com.kmxd.ams.client.event.efile.DocFileNumEvent;
import com.kmxd.ams.client.oss.IEfileRecordSvc;
import com.kmxd.ams.client.oss.vo.EfileRecordListVO;
import com.kmxd.ams.core.util.DynamicTableNameUtil;
import com.kmxd.ams.infra.arrange.base.BaseBO;
import com.kmxd.ams.infra.arrange.entity.Document;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * 修改电子文件数量
 *
 * @author ZuoLG
 */
@Slf4j
@Component
@AllArgsConstructor
public class DocFileNumCmd {
  private IDocumentSvc documentSvc;
  private IEfileRecordSvc efileRecordSvc;

  /** 修改电子文件数量 */
  @Transactional(rollbackFor = Exception.class)
  public void editFileNum(DocFileNumEvent event) throws Exception {
    // 更新电子文件数量
    BaseBO baseBO = event.getReq();
    if (StrUtil.isBlank(baseBO.getDocIds())) {
      return;
    }
    Document documentReq = new Document();
    documentReq.setTableId(baseBO.getTableId());
    documentReq.setId(Long.parseLong(baseBO.getDocIds()));
    Document document = documentSvc.view(documentReq);
    Set<Long> ids = new HashSet<>();
    if (ObjectUtil.isNotEmpty(document)) {
      ids.add(document.getId());
      List<EfileRecordListVO> efiles =
          efileRecordSvc.selectListByDocIds(baseBO.getArchTypeId(), ids);
      document.setTableId(baseBO.getTableId());
      document.setFilesNum(efiles.size());
      DynamicTableNameUtil.setTableName(baseBO.getTableId());
      documentSvc.updateById(document);
    }
  }
}
